#include "../Server.hpp"


EventLoop loop;

void WriteHandle(Socket *sock,Channel *ch,Buffer *buf)
{
    sock->Send(buf->ReadPosition(),buf->ReadAbleSize());
    ch->DisableWrite();
    ch->EnableRead();
}

void ReadHandle(Socket *sock,Channel *ch)
{
    char buffer[1024] = {0};
    ssize_t n = sock->Recv(buffer,sizeof(buffer) - 1);
    buffer[n] = 0;
    DEBUG_LOG("接收到%d号连接的消息: %s",sock->GetFd(),buffer);
    Buffer *buf = new Buffer;
    buf->WriteAndPush(buffer,strlen(buffer));

    ch->DisableRead();
    ch->SetWriteCallback(std::bind(WriteHandle,sock,ch,buf));
    ch->EnableWrite();
}

void AcceptHandle(Socket *sock)
{
    int connfd = sock->Accept();
    DEBUG_LOG("获得新连接: %d",connfd);

    Socket *connsock = new Socket(connfd);
    Channel *connch = new Channel(&loop,connsock->GetFd());
    connch->SetReadCallback(std::bind(ReadHandle,connsock,connch));
    connch->EnableRead();
}

int main()
{
    Socket lissock;
    bool ret = lissock.CreateServer(9090);
    if(ret == false)
    {
        ERROR_LOG("CREATE SERVER ERROR");
        return -1;
    }
    Channel lisch(&loop,lissock.GetFd());
    lisch.SetReadCallback(std::bind(AcceptHandle,&lissock));
    lisch.EnableRead();

    loop.Start();
    return 0;
}